#coding:utf-8
import subprocess
import time

# from FuzzCore.wfuzz.wfuzz import fuzz
# from FuzzCore.boofuzz.fuzz_logger_db import FuzzLoggerDbReader

class Test:
    def __init__(self):
        self.run_info = {}

    def boofuzzRun(self, process_name, cmd=""):
        self.run_info[process_name] = {}
        self.run_info[process_name]['isrun'] = False

        if cmd == "":
            pid_ = monitor_process(cmd)
            print(pid_)
            if pid_ == None:
                return False

            self.run_info[process_name]['p'] = None
            self.run_info[process_name]['cmd'] = cmd
            self.run_info[process_name]['pid'] = pid_
            self.run_info[process_name]['isrun'] = True
            self.run_info[process_name]['runtime'] = 0
            self.run_info[process_name]['poll'] = None
        else:
            p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=False, shell=True)
            self.run_info[process_name]['p'] = p
            self.run_info[process_name]['cmd'] = cmd
            self.run_info[process_name]['pid'] = p.pid
            self.run_info[process_name]['isrun'] = True
            self.run_info[process_name]['runtime'] = time.time()
            self.run_info[process_name]['poll'] = p.poll()

        print(self.run_info[process_name]['pid'])
        return True

    def boofuzzStat(self, process_name):
        process = self.run_info[process_name]
        print(process['pid'])
        print(process['poll'])
        p = process['poll']
        process['p'].kill()




def monitor_process(key_word):
    p1 = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE)
    p2 = subprocess.Popen(['grep', key_word], stdin=p1.stdout, stdout=subprocess.PIPE)
    p3 = subprocess.Popen(['grep', '-v', 'grep'], stdin=p2.stdout, stdout=subprocess.PIPE)
    lines = p3.stdout.readlines()
    if len(lines) > 0:
        return None

    return str(lines).split(" ")[3]



if __name__ == "__main__":
    test = Test()
    test.boofuzzRun("vsftpd")
    #test.boofuzzStat("ping")
    # monitor_process("66489")